package cn.gson.zuche.controller.user;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.gson.zuche.common.StringUtils;
import cn.gson.zuche.model.bean.User;
import cn.gson.zuche.model.dao.UserDao;
@WebServlet("/logintest1")
public class LoginTest1Servlet extends HttpServlet {
		UserDao udao = new UserDao();
		@Override
		protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			req.getRequestDispatcher("/WEB-INF/jsp/logintest1.jsp").forward(req, resp);
		}
		
		@Override
		protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			req.setCharacterEncoding("utf-8");
			resp.setCharacterEncoding("utf-8");
			
			HttpSession session = req.getSession();
			List<User> users = null;
			String userTel=req.getParameter("email");		//用户电话号码
			String password=req.getParameter("password");	//用户密码
			String logincode=req.getParameter("logincode"); //验证码
			String sesionCode = (String) req.getSession().getAttribute(CaptchaServlet.CAPTCHA_KEY);
			
//			System.out.println(sesionCode);
			/*电话号码判空*/
			if(StringUtils.isEmpty(userTel)){
				req.setAttribute("error_m", "$('.t_m').css('display','block')");
				doGet(req, resp);
				return;
			}
			if(userTel.length()!=11){
				req.setAttribute("error_m", "$('.t_m').css('display','block')");
				doGet(req, resp);
				return;
			}
			/*输入密码框判空*/
			if(StringUtils.isEmpty(password)){
				req.setAttribute("error_w", "$('.t_w').css('display','block')");
				doGet(req, resp);
				return;
			}
			
			try {
//				System.out.println(logincode);
				users = udao.findAllByPasswd(userTel,password);
//				System.out.println(users.size());
				if(users.size()==0){
					req.setAttribute("error_w", "$('.t_w').css('display','block')");
					doGet(req, resp);
					return;
				}
				/*输入验证码框判空*/
				if(StringUtils.isEmpty(logincode)){
					req.setAttribute("error_code_emp", "$('.t_code_emp').css('display','block')");
					doGet(req, resp);
					return;
				}
				/*输入验证码不正确*/
				if(!logincode.equalsIgnoreCase(sesionCode)){
					req.setAttribute("error_code", "$('.t_code').css('display','block')");
					doGet(req, resp);
					return;
				}
				session.setAttribute("userId", users.get(0).getUserId());
				
				/*User user = users.get(0);
				session.setAttribute("user", users.get(0));*/
//				System.out.println(users.get(0).getUserId());
//				System.out.println(users.size());
			} catch (SQLException e) {
				e.printStackTrace();
			}
			resp.sendRedirect(req.getContextPath()+"/main");
		}
}
